<template>
  <div id="content">
    <div id="edit-area">
      <div class="title">停车点编辑</div>
      <div class="edit-item">
        <div class="item-text">停车点名称</div>
        <template>
          <a-input
            style="width: 450px"
            v-model="inputParkName"
            placeholder="停车点名称"
          />
        </template>
      </div>
      <div class="edit-item">
        <div class="item-text">省份</div>
        <template>
          <a-input
            style="width: 450px"
            v-model="inputProvince"
            placeholder="省份"
          />
        </template>
      </div>
      <div class="edit-item">
        <div class="item-text">城市</div>
        <template>
          <a-input
            style="width: 450px"
            v-model="inputCity"
            placeholder="城市"
          />
        </template>
      </div>
      <div class="edit-item">
        <div class="item-text">区县</div>
        <template>
          <a-input
            style="width: 450px"
            v-model="inputDistrict"
            placeholder="区县"
          />
        </template>
      </div>
      <div class="edit-item">
        <div class="item-text">地址</div>
        <template>
          <a-input
            style="width: 450px"
            v-model="inputAddress"
            placeholder="地址"
          />
        </template>
      </div>
      <div class="edit-item">
        <div class="item-text">停车点坐标</div>
        <template>
          <a-input
            style="width: 450px"
            v-model="inputLngAndLat"
            placeholder="停车点坐标"
          />
        </template>
      </div>
      <div class="edit-item">
        <div class="item-text">签到范围(米)</div>
        <template>
          <a-input
            type="text"
            value=""
            onkeyup="if(this.value.length==1){this.value=this.value.replace(/[^1-9]/g,'')}else{this.value=this.value.replace(/\D/g,'')}"
            onafterpaste="if(this.value.length==1){this.value=this.value.replace(/[^1-9]/g,'')}else{this.value=this.value.replace(/\D/g,'')}"
            style="width: 450px"
            v-model="signingRange"
            placeholder="巡查人员签到范围(米)"
          />
        </template>
      </div>
      <div class="edit-item">
        <div class="item-text">联系人</div>
        <template>
          <a-input
            style="width: 450px"
            v-model="inputResponsible"
            placeholder="联系人"
          />
        </template>
      </div>
      <div class="edit-item">
        <div class="item-text">联系电话</div>
        <template>
          <a-input
            style="width: 450px"
            v-model="inputResponseTel"
            placeholder="联系电话"
          />
        </template>
      </div>
      <div class="edit-item">
        <div class="item-text">收费标准</div>
        <template>
          <a-select
            style="width: 450px"
            v-model="inputRateInfo"
            :options="rateInfoOptions"
            placeholder="收费标准"
            :allowClear="true"
          />
        </template>
      </div>
      <div class="edit-item">
        <div class="item-text">停车场类型</div>
        <template>
          <a-select
            style="width: 450px"
            v-model="type"
            :options="paringType"
            placeholder="停车场类型"
            :allowClear="true"
          />
        </template>
      </div>
      <div class="edit-item">
        <div class="item-text">所属业主</div>
        <template>
          <a-select
            style="width: 450px"
            v-model="inputLandlordId"
            :options="landlordIdOptions"
            placeholder="停车场所属业主"
            :allowClear="true"
          />
        </template>
      </div>
      <div class="edit-item" v-if="type == 2">
        <div class="item-text">泊位数量</div>
        <template>
          <a-input
            style="width: 450px"
            v-model="truckNum"
            placeholder="泊位数量"
          />
        </template>
      </div>
      <div class="edit-item" v-if="type == 2">
        <div class="item-text">道闸设备</div>
        <template>
          <el-radio-group v-model="radio" @change="radioChange">
            <el-radio label="0">单闸口</el-radio>
            <el-radio label="1">多闸口</el-radio>
          </el-radio-group>
        </template>
      </div>
      <div class="edit-item" v-if="type == 2">
        <div class="item-text" v-if="radio == 0">进出口闸:</div>
        <div class="item-text" v-if="radio == 1">进口闸:</div>
        <template>
          <a-input style="width: 450px" v-model="devicesEnter" />
        </template>
        多个以;隔开
      </div>
      <div class="edit-item" v-if="type == 2 && radio == 1">
        <div class="item-text">出口闸:</div>
        <template>
          <a-input style="width: 450px" v-model="devicesExit" />
        </template>
        多个以;隔开
      </div>
      <div class="edit-item" v-if="type == 2 || orderIngFlag ==1">
        <!-- <div class="edit-item"> -->
        <div class="item-text">缴费后免费停车时长(分钟):</div>
        <template>
          <a-input
            style="width: 450px"
            v-model="freeTime"
            placeholder="缴费后免费停车时长(分)"
          />
        </template>
      </div>
      <div class="edit-item tail">
        <a-button icon="save" @click="saveClick">保存</a-button>
        <a-button icon="rollback" @click="rollbackClick">返回</a-button>
      </div>
    </div>
    <div id="map">
      <!-- 地图 -->
      <div id="box-map" />
      <!-- 搜索框 -->
      <div id="contain-tool">
        <div id="contain-search">
          <!-- 输入框 -->
          <input
            id="keyword"
            class="input-search"
            placeholder="搜索站点位置..."
            maxlength="256"
            v-model="secrchText"
          />
          <!-- 搜索icon -->
          <img
            class="icon-search"
            @click="secrchNode"
            src="../../images/icon/search.png"
          />
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import ParkApi from "../../api/system/ParkApi";
import ChargeSettingApi from "../../api/system/ChargeSettingApi";

const marker = new AMap.Marker();

const addAndEditCondition = {
  id: "",
  parkName: "",
  province: "",
  city: "",
  district: "",
  address: "",
  coordinateX: "",
  coordinateY: "",
  signingRange: "",
  responsible: "",
  responseTel: "",
  rateInfo: "",
  landlordId: "",
  freeTime: "",
};

export default {
  name: "ParkEdit.vue",
  data() {
    return {
      inputParkName: "",
      inputContent: "",
      inputProvince: "",
      inputCity: "",
      inputDistrict: "",
      inputAddress: "",
      inputLngAndLat: "",
      inputResponsible: "",
      inputResponseTel: "",
      inputRateInfo: [],
      inputLandlordId: [],
      lng: "",
      lat: "",
      signingRange: "",
      id: "",
      type: 1,
      orderIngFlag: 0,
      truckNum: 0,
      devices: "",
      devicesExit: "",
      devicesEnter: "",
      pointMarkers: undefined,
      carPlaceMarkers: undefined,
      marker,
      rateInfoOptions: [],
      landlordIdOptions: [],
      /**其他**/
      addAndEditCondition,
      paringType: [
        { value: 1, label: "路边停车点" },
        { value: 2, label: "停车场停车点" },
      ],
      old: "",
      freeTime: "",
      radio: "0",
      secrchText: "",
    };
  },
  methods: {
    /*初始化数据*/
    initData() {
      let data = this.$route.query;
      let id = data.data;
      if (id == undefined || id == "") {
        return;
      }
      this.id = data.data.id;
      this.inputParkName = data.data.parkName;
      this.inputProvince = data.data.province;
      this.inputCity = data.data.city;
      this.inputDistrict = data.data.district;
      this.inputAddress = data.data.address;
      this.inputLngAndLat =
        data.data.coordinateX + "，" + data.data.coordinateY;
      this.lng = data.data.coordinateX;
      this.lat = data.data.coordinateY;
      this.signingRange = data.data.signingRange;
      this.inputRateInfo = data.data.rateInfo;
      this.inputLandlordId = data.data.landlordId;
      this.inputResponsible = data.data.responsible;
      this.inputResponseTel = data.data.responseTel;
      this.type = data.data.type;
      this.orderIngFlag = data.data.orderIngFlag;
      this.truckNum = data.data.sumTruckSpace;
      this.devices = data.data.devices;
      this.old = data.data.devices;
      this.freeTime = data.data.freeTime;
      this.devicesExit = data.data.devicesExit;
      this.devicesEnter = data.data.devicesEnter;
      if (
        this.devicesExit == null ||
        this.devicesExit == "" ||
        this.devicesExit == undefined
      ) {
        this.radio = "0";
      } else {
        this.radio = "1";
      }
      this.initCover();
    },
    initRateInfoOptions() {
      ChargeSettingApi.getChargeStandardTree()
        .then((data) => {
          let children = data.data.children;
          let options = [];
          if (children && children.length > 0) {
            options = children.map((x) => {
              return { value: x.id, label: x.standardName };
            });
          }
          this.rateInfoOptions = options;
        })
        .catch((err) => {
          let data = err.data;
          let msg = err.msg;
          if (data || msg) {
            return this.$message.warn(data ? data : msg ? msg : "未知error！");
          }
        });
    },
    // 初始化业主列表
    initLandlordIdOptions() {
      ChargeSettingApi.findLandlordTree()
        .then((data) => {
          let tree = data.data;
          let options = [];
          if (tree && tree.length > 0) {
            options = tree.map((x) => {
              return { value: x.landlordId, label: x.landlordName };
            });
          }
          this.landlordIdOptions = options;
        })
        .catch((err) => {
          let data = err.data;
          let msg = err.msg;
          if (data || msg) {
            return this.$message.warn(data ? data : msg ? msg : "未知error！");
          }
        });
    },

    /* ------------------------ 地图缩放事件 ------------------------ */
    initMap() {
      let data = this.$route.query;
      let lng = "";
      let lat = "";
      if (data.data == "" || data.data == undefined) {
        lng = 116.397428;
        lat = 39.90923;
      } else {
        lng = data.data.coordinateX;
        lat = data.data.coordinateY;
      }
      this.mapControl = new AMap.Map("box-map", {
        zoom: 11,
        center: [lng, lat],
        viewMode: "3D",
      });
      //https://lbs.amap.com/api/javascript-api/reference/map/
      //地图缩放级别更改后触发
      this.mapControl.on("zoomchange", this.mapZoomChange);
      //地图图块加载完成后触发事件
      this.mapControl.on("complete", this.loadData);
      this.mapControl.on("click", this.mapClick);
      this.mapControl.plugin(["AMap.Autocomplete", "AMap.PlaceSearch"], () =>
        this.pluginCallback()
      );
    },
    pluginCallback() {
      let autoOptions = {
        city: "北京", //城市，默认全国
        input: "keyword", //使用联想输入的input的id
      };
      let autocomplete = new AMap.Autocomplete(autoOptions);
      let placeSearch = new AMap.PlaceSearch({
        city: "北京",
        map: this.mapControl,
      });
      AMap.event.addListener(autocomplete, "select", (e) => {
        //TODO 针对选中的poi实现自己的功能
        placeSearch.setCity(e.poi.adcode);
        placeSearch.search(e.poi.name, (status, result) =>
          this.placeSearchCallBack(status, result)
        );
      });
    },
    placeSearchCallBack(status, result) {
      if (status == "complete") {
        let count = result.poiList.count;
        if (count > 0) {
          let pois = result.poiList.pois[0];
          let location = pois.location;
          let lng = location.lng;
          let lat = location.lat;
          this.mapControl.setCenter([lng, lat]); //设置地图中心点
          //清除所有覆盖物！
          // result.poiList = [];
          this.mapControl.clearMap();
          //根据已有的坐标新建覆盖物
          this.initCover();
        }
      } else if (status == "error") {
        console.error("搜索失败！");
      } else if (status == "no_data") {
        console.log("无搜索结果");
      } else {
        console.log("未知！");
      }
    },
    //重新绘制指示图标
    initCover() {
      let inputLngAndLat = this.inputLngAndLat;
      if (inputLngAndLat == undefined || inputLngAndLat == "") {
        return;
      }
      let lngAndLat = inputLngAndLat.split("，");
      let lng = lngAndLat[0];
      let lat = lngAndLat[1];
      let viaMarker = this.marker;
      this.mapControl.add(viaMarker);
      let position = new AMap.LngLat(lng, lat);
      viaMarker.setPosition(position);
    },
    secrchNode() {
      var keywords = this.secrchText;
      this.mapControl.plugin("AMap.PlaceSearch", () => {
        var autoOptions = {
          city: "全国",
        };
        var placeSearch = new AMap.PlaceSearch(autoOptions);
        placeSearch.search(keywords, (status, result) => {
          let lng = result.poiList.pois[0].location.lng;
          let lat = result.poiList.pois[0].location.lat;
          this.mapControl.setCenter([lng, lat]);
        });
      });
    },
    mapClick(e) {
      let lnglat = e.lnglat;
      let geocoder = new AMap.Geocoder();
      this.mapControl.add(this.marker);
      marker.setPosition(lnglat);
      this.lng = lnglat.lng;
      this.lat = lnglat.lat;
      this.inputLngAndLat = lnglat.lng + "，" + lnglat.lat;

      geocoder.getAddress(lnglat, this.geocoderCallback);
    },
    geocoderCallback(status, result) {
      if (status === "complete" && result.regeocode) {
        this.inputAddress = result.regeocode.formattedAddress;
        let province = result.regeocode.addressComponent.province;
        let city = result.regeocode.addressComponent.city;
        let district = result.regeocode.addressComponent.district;
        this.inputProvince = province;
        this.inputCity = city == undefined || city == "" ? province : city;
        this.inputDistrict = district;
      } else {
        console.error("根据经纬度查询地址失败");
      }
    },
    /**按钮**/
    saveClick() {
      //todo 新增/编辑停车点
      let condition = this.addAndEditCondition;
      condition.id = this.id;
      let parkName = this.inputParkName;
      condition.parkName = parkName;
      let province = this.inputProvince;
      condition.province = province;
      let city = this.inputCity;
      condition.city = city;
      let district = this.inputDistrict;
      condition.district = district;
      let address = this.inputAddress;
      condition.address = address;
      let coordinateX = this.lng;
      condition.coordinateX = coordinateX;
      let coordinateY = this.lat;
      condition.coordinateY = coordinateY;
      let signingRange = this.signingRange;
      condition.signingRange = signingRange;
      condition.responsible = this.inputResponsible;
      condition.responseTel = this.inputResponseTel;
      let rateInfo = this.inputRateInfo;
      condition.rateInfo = rateInfo;
      let landlordId = this.inputLandlordId;
      condition.landlordId = landlordId;
      let type = this.type;
      condition.type = type;
      let num = this.truckNum;
      condition.truckNum = num;
      // let devices =this.devices;
      let freeTime = this.freeTime;
      condition.freeTime = freeTime;

      // if(this.old==devices){
      //     condition.devices='no';
      // }else{
      //     condition.devices=devices;
      // }
      let devicesExit = this.devicesExit;
      condition.devicesExit = devicesExit;
      let devicesEnter = this.devicesEnter;
      condition.devicesEnter = devicesEnter;
      if (type === 2 && this.stringIsBlank(devicesEnter)) {
        return this.$message.warn("闸口不能为空！");
      }
      if (type === 2 && this.radio == "1" && this.stringIsBlank(devicesExit)) {
        return this.$message.warn("出闸口不能为空！");
      }
      if (this.stringIsBlank(parkName)) {
        return this.$message.warn("停车点名称不能为空！");
      }
      if (this.stringIsBlank(province)) {
        return this.$message.warn("省份不能为空！");
      }
      if (this.stringIsBlank(city)) {
        return this.$message.warn("市区不能为空！");
      }
      if (this.stringIsBlank(coordinateX)) {
        return this.$message.warn("经纬度不能为空！");
      }
      if (this.stringIsBlank(coordinateY)) {
        return this.$message.warn("经纬度不能为空！");
      }
      if (this.stringIsBlank(signingRange) && signingRange != "0") {
        return this.$message.warn("签到范围(米)不能为空！");
      }
      if (this.stringIsBlank(rateInfo)) {
        return this.$message.warn("收费标准不能为空！");
      }
      ParkApi.addPark(condition)
        .then(() => {
          this.$message.success(
            this.id == undefined || this.id == "" ? "新增成功！" : "编辑成功！"
          );
          this.rollbackClick();
        })
        .catch((err) => {
          let data = err.data;
          let msg = err.msg;
          this.$message.error(data || msg);
        });
    },
    rollbackClick() {
      // 返回上一层
      this.$router.push("/system/parkingLot");
    },
    stringIsBlank(str) {
      if (str == undefined || str == "") {
        return true;
      }
      return false;
    },
    radioChange() {
      this.devicesExit = "";
      this.devicesEnter = "";
    },
  },
  computed: {
    isHasInput() {
      return this.inputContent ? true : false;
    },
  },
  mounted() {
    this.initMap();
    this.initRateInfoOptions();
    this.initData();
    this.initLandlordIdOptions();
  },
  destroyed() {
    this.mapControl.destroy();
  },
};
</script>

<style scoped>
#content {
  width: 100%;
  height: 100%;
  position: relative;
  display: flex;
}

#map {
  width: 100%;
  height: 100%;
}

#box-map {
  width: 100%;
  height: 100%;
}

#contain-tool {
  position: absolute;
  top: 24px;
  /*left: 770px;*/
}

/* contain-search */
#contain-search {
  width: 240px;
  height: 40px;
  background: #fff;
  border-radius: 4px;
  box-shadow: 0px 1px 10px 0px rgba(201, 201, 201, 1);
  /* flex */
  display: flex;
  align-items: center;
  margin-left: 10px;
}

#contain-search .input-search {
  margin-left: 25px;
  flex: 1 1 auto;
  border: none;
  height: 100%;
  outline: none;
  /* text */
  font-size: 16px;
  color: #020202;
}

#contain-search .input-clear {
  cursor: pointer;
  width: 27px;
  height: 38px;
  background: url(//webmap1.bdimg.com/wolfman/static/common/images/new/searchbox_5c0d97d.png)
    no-repeat 0 -114px #fff;
}

#contain-search .icon-search {
  width: 20px;
  height: 20px;

  margin-left: 10px;
  margin-right: 25px;
  cursor: pointer;
}

#edit-area {
  width: 100%;
  height: 100%;
  margin: 10px;
  border: #f7f7f7 1px solid;
  overflow: scroll;
}

.title {
  margin: 0;
  border-bottom: rgba(52, 63, 49, 0.3) 1px solid;
  padding: 10px;
}

.edit-item {
  display: flex;
  align-items: center;
  margin-left: 50px;
  padding: 10px 0;
}

.edit-item .item-text {
  width: 150px;
}

.edit-item.tail {
  justify-content: center;
}

.edit-item button {
  margin: 0 10px;
}
</style>
